#!/usr/bin/env python3
# coding=utf-8

import os
import argparse
import zipfile

def unzip_file(zipfilename, unziptodir):

    print('unzip_file:', zipfilename, unziptodir)

    if not os.path.exists(unziptodir): 
        os.mkdir(unziptodir, 0o777)

    zfobj = zipfile.ZipFile(zipfilename)

    for name in zfobj.namelist():

        name = name.replace('\\', '/')

        if name.endswith('/'):
            dir = os.path.join(unziptodir, name)
            if not os.path.exists(dir):
                os.mkdir(dir)
        else:
            ext_filename = os.path.join(unziptodir, name)
            ext_dir= os.path.dirname(ext_filename)

            if not os.path.exists(ext_dir) : 
                os.mkdir(ext_dir, 0o777)

            outfile = open(ext_filename, 'wb')
            outfile.write(zfobj.read(name))
            outfile.close()


def find_hex_s19_from_zip(zip, name):
    '''

    1. unzip file.
    2. find all *.s19/*.hex.

    '''

    ecufiles = []

    destdir = '/tmp/' + name.replace('.zip', '')

    # print('zip:', zip)
    # print('destdir:', destdir)

    unzip_file(zip, destdir)

    for root, dirs, files in os.walk(destdir):

        for f in files:
            
            # print('found:', f)

            if f.endswith('hex') or f.endswith('s19'):
                ecufiles.append({'file': os.path.join(root, f), 'name': f})

    return ecufiles


def find_ecu_pkg(src):
    '''

    1. find *.zip
    2. unzip file.
    3. find *.s19/*.hex recursive.
    4. return all files.

    '''

    zipfiles = []

    for root, dirs, files in os.walk(src):
        # root The directory of file.
        # dirs all directory.
        # fiels all files.

        for f in files:
            # print(os.path.join(root, f))
            if f.endswith('.zip'):
                # print('found: ', os.path.join(root, f))
                zipfiles += find_hex_s19_from_zip(os.path.join(root, f), f)

        # for d in dirs:
            # print(os.path.join(root, d))

    return zipfiles


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--src', type=str, default=None)
    args = parser.parse_args()

    src = args.src

    if src is not None:
        files = find_ecu_pkg(src)

        print('files: ', len(files), files)

    else:
        print('error invalid args: ', src)
